<?php
namespace Event\Drive\Service;

use Event\Drive\EventParamHandle;

abstract class EventDriveService
{
    /**
     * @var string
     */
    private $requestId;

    /**
     * @var array
     */
    private $eventTaskList = [];

    public function __construct()
    {
        $this->requestId = $this->getRequestId();
    }

    /**
     * API异步事件的注册与绑定
     * @param $eventClassName
     * @param array $params
     * @return void
     */
    public function registerEventTask($eventClassName, array $params)
    {
        //参数的验证
        $data = [
            'api_domain_name' => $_SERVER['APP_URL'],
            'api_name' => $_SERVER['REQUEST_URI'],
            'event_name' => $eventClassName,
            'event_params' => json_encode((new EventParamHandle)->check($eventClassName, $params)), //已抽象
            'request_id' => $this->requestId
        ];
        //创建Task-DB
        $data['taskId'] = $this->createDBEventTask($data);
        $this->eventTaskList[] = $data;
    }

    /**
     * 异步事件的执行
     * @return void
     */
    public function execute()
    {
        if($this->eventTaskList) {
            foreach($this->eventTaskList as $eventTask) {
                $this->eventTaskMessagePush($eventTask);
            }
        }
    }

    /**
     * 请求的唯一标识
     * @return string
     */
    protected abstract function getRequestId() : string;

    /**
     * 创建Task-DB的实现
     * @param array $insertData
     * @return int
     */
    protected abstract function createDBEventTask(array $insertData) : int;

    /**
     * 处理中的代码（不抛异常或者抛异常全局不要捕捉以免影响API的正常响应）
     * @param array $eventTask
     * @return void
     */
    protected abstract function eventTaskMessagePush(array $eventTask) : void;
}
